package com.lkm.market2_0;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.lkm.comlib.AppBridge;
import com.lkm.comlib.AppBridgeBase;
import com.lkm.comlib.Config;
import com.lkm.comlib.MyApplicationL;
import com.lkm.comlib.fun_m.NetworkStateModule;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.module.PermissionHandleAdapterImpl;
import com.lkm.comlib.net.http.OkHttpDownload;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.P;
import com.lkm.frame.file.FileSystem;
import com.lkm.frame.module.ModuleManager;
import com.lkm.frame.net.imageload.AsyncImageLoaderLs;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskManager;
import com.lkm.frame.task2.TaskManagerImple;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.m.appserver.AppMainModule;
import com.lkm.market2_0.m.dataUp.DataUpModule;
import com.lkm.market2_0.m.dataUp.DetaUpModuleDelegate;
import com.lkm.market2_0.m.imple.appserver.AppMainModuleDelegate;
import com.lkm.market2_0.m.imple.appserver.AppMainModuleImple;
import com.lkm.market2_0.m.imple.steelyarddata.SteelyardDataModuleDelegate;
import com.lkm.market2_0.m.imple.steelyardserver.SteelyardServerModuleDelegate;
import com.lkm.market2_0.m.imple.steelyardstatus.SteelyardStatusModuleDelegate;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyardserver.SteelyardServerModule;
import com.lkm.market2_0.m.steelyardstatus.SteelyardStatusManagerModule;
import com.lkm.market2_0.netapi.Api;
import com.lkm.market2_0.push.PushSetGoodsButtonHandle;
import com.lkm.market2_0.push.PushSetSteelyardRepairingHandle;
import com.lkm.market2_0.steelyard.SteelyardServerModuleDelegateBluetooth;
import com.lkm.market2_0.steelyards.SteelyardServerModuleDelegateSerialport;
//import com.lkm.steelyardmodules.nfc.NFC_Module;
//import com.lkm.steelyardmodules.nfc.OnFinderCardListener;
import com.mj.hx.yl.push.OnReceiverPushListener;
import com.mj.hx.yl.push.PushManage;
import com.mj.hx.yl.push.PushType;

import java.util.concurrent.Executor;


/**
 *
 * app流程：1，启动推送。2，推送启动成功后 开始初始化 AppMainModule模块。3，AppMainModule模块在启动之前会拉取机构信息syncAllOrgInfoForS
 * Created by lkm on 17-1-4.
 */

public class MyApplication extends MyApplicationL implements OnReceiverPushListener{


    private ModuleManager mModuleManager;

    private TaskManager mTaskManager2;
    private MainPresenter mMainPresenter;

    public MainPresenter getMainPresenter() {
        return mMainPresenter;
    }

    @Override
    public void onCreate() {
        //启动推送模块
        PushManage.init(this,new PushType[]{
                new PushType(3, PushSetGoodsButtonHandle.class),
                new PushType(5, PushSetSteelyardRepairingHandle.class),

        });

//        P.p("===="+getCurProcessName(this));
//        mark.satrace.cn:channel
        if(getCurProcessName(this).contains(":channel")){
            P.p("====跳出推送的进程");
            //推送的
            return;
        }

        HoldService.start(this);
        super.onCreate();
    }

    @Override
    protected void init() {
        P.isDebug=true;
        mMainPresenter = new MainPresenter(new Market2_0ConfigeImpl());
        mMainPresenter.init();
//        com.lkm.market2_0.Config.instance=new Market2_0ConfigeImpl();
        super.init();
        Api.init();
        String ip =  getSharedPreferences("settingapp",Context.MODE_PRIVATE).getString("tv_url", "http://zhongzi.web.ic1986.com/api/tc.ashx");//"http://192.168.1.172:8080/api/xx.jsp");
        Api.host = ip;

        NetworkStateModule.getInstance().start(this);

        mTaskManager2=new TaskManagerImple();
        mModuleManager=new ModuleManager(new PermissionHandleAdapterImpl(this),mTaskManager2,new Handler(Looper.getMainLooper()));

        //app主程序
        mModuleManager.register(AppMainModule.class, AppMainModuleDelegate.class);
        //台秤通讯的服务器
        mModuleManager.register(SteelyardServerModule.class, SteelyardServerModuleDelegateSerialport.class);
//        mModuleManager.register(SteelyardServerModule.class, SteelyardServerModuleDelegate.class);
        //台秤数据管理
        mModuleManager.register(SteelyardDataModule.class, SteelyardDataModuleDelegate.class);
        //台秤状态管理
        mModuleManager.register(SteelyardStatusManagerModule.class, SteelyardStatusModuleDelegate.class);

        mModuleManager.register(DataUpModule.class, DetaUpModuleDelegate.class);

//        mModuleManager.register(NFC_Module.class, NFC_ModuleHSJ800ModuleDelegate.class);
//
//
//        mModuleManager.getModule(NFC_Module.class, new RunnablePR<Boolean, Void>() {
//            @Override
//            public Void run(Boolean aBoolean) {
//                P.p("==== 加载NFC"+aBoolean);
//                NFC_Module nfc_module = mModuleManager.loadModule(NFC_Module.class);
//
//                nfc_module.connect(true);
//                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        nfc_module.getPaySignCheck();
////                        nfc_module.waitForReadCardNum(new OnFinderCardListener() {
////                            @Override
////                            public void onFinderCard(String carNum) {
////                                new Handler(Looper.getMainLooper()).post(new Runnable() {
////                                    @Override
////                                    public void run() {
////                                        ViewUIHelp.showTipsLong(BaseFragmentActivity.getLastActivity(),carNum);
////                                    }
////                                });
////                                System.out.println("====读到卡号 "+carNum);
////                            }
////                        });
//                    }
//                },5000);
//
//                return null;
//            }
//        });



        //启动主模块，开始运行。//放到加载成功LoadAppInitForSTask
//        mModuleManager.loadModule(AppMainModule.class);


        getTaskManager2().setBCToAll("app_saveOrder_TaskId",new BackCallAdapter< Void, Boolean> (){
            @Override
            public void onFinish(Task<?, Void, Boolean> task, Boolean aBoolean) {
                super.onFinish(task, aBoolean);
                Object[] o = (Object[]) task.getParam();
                Object p = o[0];
                OrderEntity orderEntity = (OrderEntity) p;

                Intent intent = new Intent("com.ast.market2_0.action.ORDER");
                intent.putExtra("order", new Gson().toJson(orderEntity));
                MyApplication.getInstance().sendBroadcast(intent);
            }
        });
    }

    public ModuleManager getModuleManager(){
        return mModuleManager;
    }

    public TaskManager getTaskManager2() {
        return mTaskManager2;
    }

    @Override
    public boolean isDebug() {
        return BuildConfig.DEBUG;
    }


    public static MyApplication getInstance(Context c) {
        return (MyApplication) c.getApplicationContext();
    }
    public static MyApplication getInstance( ) {
        return (MyApplication) application;
    }




//    @Override
    public AsyncImageLoaderLs createAsyncImageLoaderLs() {
        return new AsyncImageLoaderLs(getApplicationContext(), new OkHttpDownload(getApplicationContext()) {

            @Override
            protected void onBuilder(com.squareup.okhttp.Request.Builder builder) {
                super.onBuilder(builder);

//                String Authorization = MyApplication.this.getUserInfoCache().getAuthorization(MyApplication.this);
//                FXBM.D();// 有空重构一下
//                if (!StringUtils.isEmpty(Authorization)) {
//                    builder.addHeader("Authorization", Authorization);
//                }

            }
        }, Config.getImageDownExecutor(), FileSystem.FileLocal.ExternalCacheDir, "imgs");
    }


    @Override
    public AppBridge getAppBridge() {
        return new AppBridge() {

            @Override
            public void goLaunchActivity(Context c) {
                //// TODO: 17/12/5
            }

            @Override
            public String upError(Context c, String app_name, String app_version, String error) {
                return null;
            }
        };
    }



    @Override
    public String getSDRootDir() {
        return "";
    }
    @Override
    public int getPhoneMinMemorySize() {
        return 0;
    }

    private AppBridgeBase mAppBridgeBase=new AppBridgeBase() {
        @Override
        public AsyncImageLoaderLs createAsyncImageLoaderLs() {
            return MyApplication.this.createAsyncImageLoaderLs();
        }

        @Override
        public Executor getTaskExecutor() {
            return Config.getTaskExecutor();
        }
    };

    @Override
    public AppBridgeBase getAppBridgeBaseInstance() {
        return mAppBridgeBase;
    }


    @Override
    public boolean onReceiverPush_TextMessage(String data) {
        return false;
    }

    @Override
    public void onReceiverPushClientID(String clientid) {
        AppDataCache.getInstance().setPushKey(clientid);
//        mMainPresenter.syncAllOrgInfoForS
//        LoadAppInitForSTask.load(AppDataCache.getInstance().getPushKey());

        
        AppMainModuleImple appMainModuleImple= (AppMainModuleImple) com.lkm.market2_0.Config.instance.getModuleManager().loadModule(AppMainModule.class);


        


    }
}
